package com.obj.commpont.common.utils;

import org.apache.commons.lang3.ArrayUtils;

public class HexUtils {

    public static final char[] DIGITS = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray();

    public static final char[] DIGITS_NOCASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

    public static final char[] DIGITS_62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

    /**
     * 将一个byte数组转换成62进制的字符串。
     */
    public static String bytesToString(byte[] bytes) {
        return bytesToString(bytes, false);
    }

    /**
     * 将一个byte数组转换成62进制的字符串。
     *
     * @param bytes  源数组
     * @param noCase 是否采用小写字母
     */
    public static String bytesToString(byte[] bytes, boolean noCase) {
        char[] digits = noCase ? DIGITS_NOCASE : DIGITS;
        int digitsLength = digits.length;

        if (ArrayUtils.isEmpty(bytes)) {
            return String.valueOf(digits[0]);
        }

        StringBuilder strValue = new StringBuilder();
        int value = 0;
        int limit = Integer.MAX_VALUE >>> 8;
        int i = 0;

        do {
            while (i < bytes.length && value < limit) {
                value = (value << 8) + (0xFF & bytes[i++]);
            }

            while (value >= digitsLength) {
                strValue.append(digits[value % digitsLength]);
                value = value / digitsLength;
            }
        } while (i < bytes.length);

        if (value != 0 || strValue.length() == 0) {
            strValue.append(digits[value]);
        }

        return strValue.toString();
    }

    /**
     * 将一个长整形转换成62进制的字符串。
     */
    public static String longToString(long longValue) {
        return longToString(longValue, false);
    }

    /**
     * 将一个长整形转换成62进制的字符串。
     */
    public static String longToString(long longValue, boolean noCase) {
        char[] digits = noCase ? DIGITS_NOCASE : DIGITS;
        int digitsLength = digits.length;

        if (longValue == 0) {
            return String.valueOf(digits[0]);
        }

        if (longValue < 0) {
            longValue = -longValue;
        }

        StringBuilder strValue = new StringBuilder();

        while (longValue != 0) {
            int digit = (int) (longValue % digitsLength);
            longValue = longValue / digitsLength;

            strValue.append(digits[digit]);
        }

        return strValue.toString();
    }

    /**
     * 将int转换为62进制的显示形式
     *
     * @param num 转换前的数字
     * @return 62进制表示字符串
     */
    public static String encode62(int num) {
        int num1 = (num / (62 * 62)) % 62;
        int num2 = (num / 62) % 62;
        int num3 = num % 62;

        StringBuilder numCode = new StringBuilder();
        numCode.append(String.valueOf(DIGITS_62).charAt(num1))
                .append(String.valueOf(DIGITS_62).charAt(num2))
                .append(String.valueOf(DIGITS_62).charAt(num3));
        return numCode.toString();
    }

}
